/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.rtservice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.inspur.edp.lcm.metadata.api.entity.*;
import com.inspur.edp.lcm.metadata.common.MetadataDtoConverter;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhaoleitr
 */
public class MetadataRtUtils {
	public List<Metadata4Ref> buildMetadata4RefList(String dtosStr){
		if(StringUtils.isEmpty(dtosStr)){
			return null;
		}
		List<Metadata4RefDto> dtoList=deserializerMetadata4RefDto(dtosStr);
		if(dtoList==null||dtoList.size()<=0){
			return null;
		}
		List<Metadata4Ref> metadataList=new ArrayList<>();
		for(Metadata4RefDto dto: dtoList){
			Metadata4Ref metadata4Ref=new Metadata4Ref();
			metadata4Ref.setPackageHeader(dto.getPackageHeader());
			metadata4Ref.setMetadata(MetadataDtoConverter.asMetadata(dto.getMetadata()));
			metadata4Ref.setServiceUnitInfo(dto.getServiceUnitInfo());
			metadataList.add(metadata4Ref);
		}
		return metadataList;
	}
	private List<Metadata4RefDto> deserializerMetadata4RefDto(String content) {
		List<Metadata4RefDto> result=new ArrayList<>();
		ObjectMapper mapper = new ObjectMapper();
		mapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
		mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

		try {
			result= mapper.readValue(content, new TypeReference<ArrayList<Metadata4RefDto>>(){});
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return result;
	}

	public String serializerMetadataRtFilter(MetadataRTFilter filter) {
		String result="";
		ObjectMapper mapper = new ObjectMapper();
		mapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
		try {
			result = mapper.writeValueAsString(filter);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return result;
	}
}
